package sample.business.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;

/**
 * Created by lilongfei on 2016/12/18.
 */
public class FreemarkerUtil {

    private static  Configuration configuration = null;
    static {
        configuration = new Configuration(Configuration.VERSION_2_3_23);
        configuration.setDefaultEncoding("utf-8");

        try {
            configuration.setDirectoryForTemplateLoading(new File(
                    FreemarkerUtil.class.getResource("../").getPath()
                    + File.separator + "ftl" +File.separator));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void createXml(String name,Object data,String dist) throws Exception{
        Template template = configuration.getTemplate(name);
        FileWriter fileWriter = new FileWriter(dist);
        template.process(data,fileWriter);
        fileWriter.close();
    }

    public static String readContent(String name,Object data){
        StringWriter stringWriter = new StringWriter();
        try {
            Template template = configuration.getTemplate(name);
            template.process(data,stringWriter);
            return stringWriter.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }finally {
            try {
                stringWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args){
        System.out.println(FreemarkerUtil.readContent("spring.ftl",null));
    }
}
